package com.ca.ui.core.view.bar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ca.ui.core.R;

import java.util.ArrayList;
import java.util.List;

public class MiniScoreProcessBar extends ConstraintLayout {

    public static final int SCORE_ID = R.drawable.ic_star;
    public static final int SCORE_SECOND_ID = R.drawable.ic_star_second;

    private int score;

    private List<ImageView> scoreViewList = new ArrayList<>();

    public ImageView iv1;
    public ImageView iv2;
    public ImageView iv3;
    public ImageView iv4;
    public ImageView iv5;

    public MiniScoreProcessBar(@NonNull Context context, int score) {
        super(context);
        this.score = score;
        initView(context, null);
    }

    public MiniScoreProcessBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public MiniScoreProcessBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        View view = LayoutInflater.from(context).inflate(R.layout.mini_score_process_bar_layout, this);
        iv1 = view.findViewById(R.id.iv_1);
        iv2 = view.findViewById(R.id.iv_2);
        iv3 = view.findViewById(R.id.iv_3);
        iv4 = view.findViewById(R.id.iv_4);
        iv5 = view.findViewById(R.id.iv_5);

        //  添加五颗星
        scoreViewList.add(iv1);
        scoreViewList.add(iv2);
        scoreViewList.add(iv3);
        scoreViewList.add(iv4);
        scoreViewList.add(iv5);

        if (attrs != null) {
            TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MiniScoreProcessBar, 0, 0);

            score = array.getInteger(R.styleable.MiniScoreProcessBar_mspb_score, 0);

            array.recycle();
        }

        setScore(score);
    }

    public int getScore() {
        return score;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setScore(int score) {
        this.score = score;
        for (int i = 0; i < this.scoreViewList.size(); i++) {
            ImageView imageView = scoreViewList.get(i);
            int id;
            if (i < score) {
                id = SCORE_ID;
            }
            else {
                id = SCORE_SECOND_ID;
            }
            imageView.setImageDrawable(getResources().getDrawable(id));
        }
    }

    public ImageView get(int index) {
        return scoreViewList.get(index);
    }
}
